package binarytree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 21:25
 * https://leetcode-cn.com/problems/symmetric-tree/
 * 给你一个二叉树的根节点 root ， 检查它是否轴对称。
 */
public class IsSymmetric {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 迭代法判断 使用队列或者栈都可以，重点做左孩子的左子树和右孩子的右子树相等  左孩子的右子树和右孩子的左子树相等（这里不是层次遍历）
     * @param root
     * @return
     */
    public boolean isSymmetric1(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> levelNodes = new LinkedList<>();
        levelNodes.offer(root.left);
        levelNodes.offer(root.right);
        while (!levelNodes.isEmpty()) {
            TreeNode left = levelNodes.poll();
            TreeNode right = levelNodes.poll();
            if (left == null && right == null) {
                //继续比较队里的下一组；
                continue;
            } else if (left == null && right != null) {
                return false;
            } else if (left != null && right == null) {
                return false;
            } else if (left.val != right.val) {
                return false;
            }
            levelNodes.offer(left.left);
            levelNodes.offer(right.right);
            levelNodes.offer(left.right);
            levelNodes.offer(right.left);
        }
        return true;
    }

    /**
     * 递归 判断根节点的左右子树是否相等
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        return compare(left, right);
    }



    private boolean compare(TreeNode left, TreeNode right) {
        if (left == null && right == null) {
            return true;
        } else if (left == null && right != null) {
            return false;
        } else if (left != null && right == null) {
            return false;
        } else if (left.val != right.val) {
            return false;
        } else {
            return compare(left.left, right.right) && compare(left.right, right.left);
        }
    }

    public static void main(String[] args) {

    }
}
